package lightswitch.server.code.sqlhelper.statement.select;

import java.util.ArrayList;
import java.util.List;

import lightswitch.server.code.sqlhelper.ExpressionHelper;
import lightswitch.server.code.sqlhelper.expression.Expression;
import lightswitch.server.code.sqlhelper.expression.NormalTable;
import lightswitch.server.code.sqlhelper.expression.ResultTable;
import lightswitch.server.code.sqlhelper.expression.AbstractTable;
import lightswitch.server.code.util.StringHelper;

public class From {
	public List<AbstractTable> _tableList;
	public List<Expression> _joinExpression;

	public From() {

	}

	public From(String statement, From fr) {
		_tableList = new ArrayList<AbstractTable>();
		if (statement == "")
			return;

		_tableList = new ArrayList<AbstractTable>();
		_joinExpression = new ArrayList<>();

		statement  = StringHelper.NormalizeString(statement);
		statement = statement.substring("from".length());

		statement = statement.replace(",", "join");

		String tempStrList[] = statement.split("join");

		List<String> strList = new ArrayList<>();
		for (int i = 0; i < tempStrList.length; i++) {
			String temp = tempStrList[i];
			if (StringHelper.CheckParenthesis(temp)) {
				strList.add(temp);
			} else {
				do {
					i++;
					temp += (" join " + tempStrList[i]);
				} while (!StringHelper.CheckParenthesis(temp));
				strList.add(temp);
			}

		}

		for (int i = 0; i < strList.size(); i++) {
			AbstractTable tb;
			if (strList.get(i).contains("select")) {
				tb = new ResultTable(strList.get(i));
				Expression ex = ExpressionHelper.parseExpression("true", null);
				_joinExpression.add(ex);
			} else {
				String[] items = strList.get(i).split("on");
				if (items.length == 2) {
					tb = new NormalTable(items[0]);
					Expression ex = ExpressionHelper.parseExpression(items[1],
							null);
					_joinExpression.add(ex);
				} else {
					if (items.length == 1) {
						tb = new NormalTable(items[0]);
						Expression ex = ExpressionHelper.parseExpression(
								"true", null);
						_joinExpression.add(ex);
					} else {
						// throw exception;
						return;
					}
				}
			}
			_tableList.add(tb);

		}
	}

	public String toString() {
		String t = "";

		t += "FROM ";
		for (int i = 0; i < _tableList.size(); i++) {
			t = t + _tableList.get(i).toString() + ", ";
		}

		return t;
	}

}
